package com.cxm.helper.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cxm.helper.exception.BusinessException;
import com.cxm.helper.pojo.Article;
import com.cxm.helper.pojo.Category;
import com.cxm.helper.pojo.Config;
import com.cxm.helper.pojo.User;
import com.cxm.helper.pojo.dto.ArticleListDTO;
import com.cxm.helper.pojo.vo.ArticleVO;
import com.cxm.helper.service.*;
import com.cxm.helper.mapper.ArticleMapper;
import com.cxm.helper.util.BeanUtil;
import com.cxm.helper.util.response.PageResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author chenximeng
 * @description 针对表【article】的数据库操作Service实现
 * @createDate 2022-11-22 16:57:54
 */
@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article>
        implements ArticleService {

    @Autowired
    UserService userService;
    @Autowired
    CategoryService categoryService;
    @Autowired
    ArticleMapper articleMapper;
    @Autowired
    UserLikeService userLikeService;
    @Autowired
    ConfigService configService;


    @Override
    public PageResponse<ArticleVO> listArticle(ArticleListDTO articleListDTO) {
        QueryWrapper<Article> wrapper = new QueryWrapper<>();
        if (CollUtil.isNotEmpty(articleListDTO.getCategoryIds())) {
            wrapper.in("category_id", articleListDTO.getCategoryIds());
        }
        Page<Article> page = new Page<>(-1, -1);
        if (articleListDTO.getCurrent() != null) {
            page = new Page<>(articleListDTO.getCurrent(), articleListDTO.getSize());
        }
        if (CollUtil.isNotEmpty(articleListDTO.getStatusList())) {
            wrapper.in("status", articleListDTO.getStatusList());
        }
        if (StrUtil.isNotBlank(articleListDTO.getKeyword())) {
            wrapper.like("title", articleListDTO.getKeyword())
                    .or().like("content", articleListDTO.getKeyword());
        }
        wrapper.orderByDesc("topping");
        wrapper.orderByDesc("id");
        List<Article> list = articleMapper.selectPage(page, wrapper).getRecords();
        if (CollUtil.isEmpty(list)) {
            return new PageResponse<>(page, CollUtil.newArrayList());
        }

        return new PageResponse<>(page, formatArticles(list));
    }

    private List<ArticleVO> formatArticles(List<Article> list) {
        List<ArticleVO> result = BeanUtil.copyList(list, ArticleVO.class);
        List<Long> articleIds = result.stream().map(ArticleVO::getId).collect(Collectors.toList());
        List<Long> userIds = result.stream().map(ArticleVO::getCreateUser).collect(Collectors.toList());
        List<Long> categoryIds = result.stream().map(ArticleVO::getCategoryId).collect(Collectors.toList());
        Map<Long, User> userMap = userService.listByIds(userIds).stream().collect(Collectors.toMap(User::getId, user -> user));
        Map<Long, Category> categoryMap = categoryService.listByIds(categoryIds).stream().collect(Collectors.toMap(Category::getId, category -> category));
        Map<Long, Integer> likeStatusMap = userLikeService.articleListIsLiked(articleIds, StpUtil.getLoginIdAsLong());
        Map<Long, Long> redisLikedNumMap = userLikeService.getArticleLikedNumFromRedis(articleIds, false);
        List<String> majorCodeList = userMap.values().stream().map(User::getMajorCode).collect(Collectors.toList());
        Map<String, String> majorCodeMap = configService.getByConfigNames(majorCodeList).stream().collect(Collectors.toMap(Config::getConfigName, Config::getConfigValue));
        for (ArticleVO articleVO : result) {
            User user = userMap.get(articleVO.getCreateUser());
            articleVO.setCategory(categoryMap.get(articleVO.getCategoryId()));
            articleVO.setCreateUserNickname(user.getNickname());
            articleVO.setLikedNum(redisLikedNumMap.get(articleVO.getId()) == null ?
                    articleVO.getLikedNum() : articleVO.getLikedNum() + redisLikedNumMap.get(articleVO.getId()));
            articleVO.setCreateUserAvatar(userMap.get(articleVO.getCreateUser()).getAvatar());
            articleVO.setFileList(CollUtil.newArrayList(articleVO.getFileUrls().split(",")));
            articleVO.setLikeStatus(likeStatusMap.get(articleVO.getId()));
            articleVO.setCreateUserMajorName(majorCodeMap.get(user.getMajorCode()));
        }
        return result;
    }

    @Override
    public ArticleVO getVoById(Long id) {
        Article article = getById(id);
        if (article == null) {
            throw new BusinessException("帖子不存在");
        }
        return formatArticles(CollUtil.newArrayList(article)).get(0);
    }
}




